package cn.lsoft.dao.mongodb;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;

/**
 * Mongo工具类:设计为单例模式，每当月份发生变化，数据库连接名称就会发生变化，这是业务规则 因MongoDB的Java驱动是线程安全的，对于一般的应用，只要一个Mongo实例即可，Mongo有个内置的连接池（池大小默认为10个）。
 * 对于有大量写和读的环境中，为了确保在一个Session中使用同一个DB时，我们可以用以下方式保证一致性： DB mdb =mongo.getDB('dbname'); mdb.requestStart(); // 业务代码 mdb.requestDone();
 * DB和DBCollection是绝对线程安全的
 * @author wujintao
 */
public class MongoInit {
	/** DB监听端口号 */
	private static int DBPort = 27017;
	/** DB连接URL */
	private static String DBUrl = "localhost";
	/** 连接DB库名称 */
	private static String DBName = "wlwdb";
	static Logger log = Logger.getRootLogger();
	private static Mongo mongo;
	private static DBCollection coll;
	private static DB db;

	static {
		try {
			DBproperties();
			MongoOptions options = new MongoOptions();
			options.autoConnectRetry = true;
			options.connectionsPerHost = 1000;
			options.maxWaitTime = 5000;
			options.socketTimeout = 0;
			options.connectTimeout = 15000;
			options.threadsAllowedToBlockForConnectionMultiplier = 5000;
			// 事实上，Mongo实例代表了一个数据库连接池，即使在多线程的环境中，一个Mongo实例对我们来说已经足够了
			ServerAddress serverAddress = new ServerAddress(DBUrl, DBPort);
			mongo = new Mongo(serverAddress, options);
		} catch (UnknownHostException e) {
			log.info("get mongo instance failed");
		}
	}

	static void DBproperties() {
		// 读取配置文件config.properties中的属性值
		String myFilePath = MongoInit.class.getResource("/").getPath() + "MongoDBConfig.properties";
		Properties properties = new Properties();
		FileInputStream fileInputStream = null;
		try {
			   fileInputStream = new FileInputStream(myFilePath);
			   properties.load(fileInputStream);
			   DBPort = Integer.parseInt((String) properties.getProperty("DBPort"));
			   DBUrl = (String) properties.getProperty("DBUrl");
			   DBName = (String) properties.getProperty("DBName");
			  } catch (Exception e) {
			   e.printStackTrace();
			  } finally {
			   try {
			    fileInputStream.close();
			   } catch (IOException e) {
			    // TODO Auto-generated catch block
			    e.printStackTrace();
			   }
		}

	}

	public static DB getDB() {
		if (db == null) {
			db = mongo.getDB(DBName);
		}
		return db;
	}

	public static Mongo getMong() {
		return mongo;
	}

	public static DBCollection getColl(String collname) {
		return getDB().getCollection(collname);
	}

}